package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.driver.config.TxCloudProperty;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    private final TxCloudProperty cosProperty;
    /**
     * 文件上传
     *
     * @param file
     * @param path
     * @return
     */
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        COSClient cosClient = getCosClient();

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentEncoding("UTF-8");

        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String fileExtName =
                file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-","");
        String key = "driver/" + path + "/" + fileName + fileExtName;
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(
                    cosProperty.getBucketPrivate(), key, file.getInputStream() , objectMetadata);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        String url = getImageUrl(key);
        cosClient.shutdown();
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(key);
        cosUploadVo.setShowUrl(url);

        return cosUploadVo;
    }

    /**
     * 获取图片预签名
     * @param key 图片对象键
     * @return
     */
    @Override
    public String getImageUrl(String key) {
        COSClient cosClient = getCosClient();
        Date date = new DateTime().plusMinutes(15).toDate();
        URL url = cosClient.generatePresignedUrl(cosProperty.getBucketPrivate(),
                key,
                date,
                HttpMethodName.GET);
        return url.toString();
    }

    /**
     * 获取cos对象存储服务器客户端
     * @return
     */
    private COSClient getCosClient() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(
                cosProperty.getSecretId(), cosProperty.getSecretKey());
        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        Region region = new Region(cosProperty.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }
}
